const router = require('koa-router')()
const {getList, getDetail, newBlog, updateBlog, delBlog} = require('../controller/blog.js');
const {SuccessModel, ErrorModel} = require('../model/resModel.js');
const loginCheck= require('../middleware/loginCheck.js');
router.prefix('/api/blog')

router.get('/list', async (ctx, next) =>{
  let author = ctx.query.author || ''
  let keyword = ctx.query.keyword || ''
  if (ctx.query.isadmin) {
    if (ctx.session.username == undefined) {
      ctx.body = new ErrorModel('登入失败')
      return
    }
    author = ctx.session.realname
  }
  const data = await getList(author, keyword) //返回promise
   ctx.body = new SuccessModel(data)
  
})

router.get('/detail', async (ctx, next)=> {
  let listData =await getDetail(ctx.query.id)
  ctx.body = new SuccessModel(listData)
})

router.post('/new',loginCheck,async (ctx,next)=>{
  const body = ctx.request.body
  body.author=ctx.session.realname
  const data = await newBlog(body)
  ctx.body = new SuccessModel(data)
})

router.post('/update',loginCheck,async (ctx,next)=>{
  const value = await updateBlog(ctx.query.id,ctx.request.body)
    if (value) {
      ctx.body = new SuccessModel('更新成功')
    }else {
      ctx.body = new ErrorModel('更新博客失败')
    }
    
})

router.post('/del',loginCheck,async (ctx,next)=>{
  const value = await delBlog(ctx.query.id,ctx.session.realname)
    if (value) {
      ctx.body =  new SuccessModel('删除成功')
    } else {
      ctx.body = new ErrorModel('删除失败')
    }
})
module.exports = router
